<template>
  <view class="category-page">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <uni-search-bar placeholder="爆款零食低至5折" bgColor="#f7f7f7" radius="20" />
    </view>

    <!-- 横向一级分类（大图标） -->
    <scroll-view class="level1-scroll" scroll-x>
      <view
          v-for="(item, idx) in level1Categories"
          :key="item.id"
          :class="['level1-item', idx === activeL1Index ? 'active' : '']"
          @click="handleLevel1Click(idx)"
      >
        <image :src="item.icon || '/static/logo.png'" class="level1-img" />
        <text class="level1-name">{{ item.categoryName }}</text>
      </view>
    </scroll-view>

    <!-- 悬浮的全部分类按钮（美化后） -->
    <view class="float-all-btn" @click="showAllCategory = true">
      <uni-icons type="list" size="22" color="#fff" style="margin-right:8rpx;" />
      <text class="float-all-text">全部分类</text>
    </view>

    <!-- 全部分类弹窗 -->
    <view v-if="showAllCategory" class="all-category-modal">
      <view class="all-category-content">
        <view class="all-title">全部分类</view>
        <view class="all-category-list">
          <view
              v-for="(item, idx) in level1Categories"
              :key="item.id"
              :class="['all-category-item', idx === activeL1Index ? 'active' : '']"
              @click="handleLevel1Click(idx); showAllCategory = false"
          >
            <image :src="item.icon || '/static/logo.png'" class="all-category-img" />
            <text class="all-category-name">{{ item.categoryName }}</text>
          </view>
        </view>
        <view class="all-close-btn" @click="showAllCategory = false">点击收起 ^</view>
      </view>
    </view>

    <view class="main-content">
      <!-- 左侧二级分类 -->
      <scroll-view class="level2-scroll" scroll-y>
        <view
            v-for="(item, idx) in level2Categories"
            :key="item.id"
            :class="['level2-item', idx === activeL2Index ? 'active' : '']"
            @click="handleLevel2Click(item, idx)"
        >
          <text>{{ item.categoryName }}</text>
        </view>
      </scroll-view>

      <!-- 右侧商品区 -->
      <view class="product-area">
        <!-- 筛选tab -->
        <view class="filter-tabs">
          <text :class="{active: sortType==='comprehensive'}" @click="sortType='comprehensive'">综合</text>
          <text :class="{active: sortType==='sales'}" @click="sortType='sales'">销量</text>
          <text :class="{active: sortType==='price'}" @click="sortType='price'">价格</text>
        </view>
        <!-- 商品列表（用排序后的列表） -->
        <view
            v-for="product in sortedProductList"
            :key="product.id"
            class="product-item"
            @click="goToProductDetail(product.id)"
        >
          <image class="product-image" :src="product.imageUrl || '/static/logo.png'" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{ product.goodsName }}</text>
            <text class="product-desc">{{ product.introduce }}</text>
            <view class="price-line">
              <text class="product-price">¥{{ product.price }}</text>
              <text class="product-sales">销量：{{ product.sales == null ? 0 : product.sales }}</text>
              <uni-icons class="add-icon" type="plus-filled" size="24" color="#ff4d4f" @click="handleAddCart(product)"></uni-icons>
            </view>
          </view>
        </view>
        <uni-load-more :status="loadingStatus"></uni-load-more>
      </view>
    </view>
  </view>
</template>

<script>
// 保留你的原有逻辑和方法
import { getPageInitData, getGoodsListByCategory } from '@/api/prodcut';
import { addCart } from '@/api/cart';

export default {
  data() {
    return {
      categoryTree: [],
      productList: [],
      activeL1Index: 0,
      activeL2Index: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      currentCategoryId: null,
      loadingStatus: 'more',
      sortType: 'comprehensive', // 新增：排序类型
      showAllCategory: false, // 控制全部分类弹窗显示
    };
  },
  computed: {
    level1Categories() {
      return this.categoryTree;
    },
    level2Categories() {
      if (this.categoryTree && this.categoryTree.length > 0 && this.categoryTree[this.activeL1Index]) {
        return this.categoryTree[this.activeL1Index].children || [];
      }
      return [];
    },
    // 新增：排序后的商品列表
    sortedProductList() {
      let list = [...this.productList];
      if (this.sortType === 'sales') {
        list.sort((a, b) => (b.sales || 0) - (a.sales || 0));
      } else if (this.sortType === 'price') {
        list.sort((a, b) => (a.price || 0) - (b.price || 0)); // 升序
      }
      return list;
    }
  },
  onLoad() {
    this.loadInitialData();
  },
  methods: {
    async loadInitialData() {
      try {
        uni.showLoading({ title: '加载中...' });
        const res = await getPageInitData();
        this.categoryTree = res.data.categoryTree;
        this.productList = res.data.productList || [];
        if (this.level2Categories && this.level2Categories.length > 0) {
          this.currentCategoryId = this.level2Categories[0].id;
        }
        this.checkIfNoMore(this.productList);
      } catch (error) {
        console.error('初始化数据加载失败', error);
        uni.showToast({ title: '数据加载失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },
    handleLevel1Click(index) {
      if (this.activeL1Index === index) return;
      this.activeL1Index = index;
      this.activeL2Index = 0;
      const firstL2Category = this.level2Categories && this.level2Categories[0];
      if (firstL2Category) {
        this.handleLevel2Click(firstL2Category, 0);
      } else {
        this.productList = [];
        this.currentCategoryId = null;
        this.loadingStatus = 'noMore';
      }
    },
    handleLevel2Click(category, index) {
      this.activeL2Index = index;
      if (this.currentCategoryId === category.id) return;
      this.currentCategoryId = category.id;
      this.productList = [];
      this.queryParams.pageNum = 1;
      this.loadingStatus = 'more';
      this.loadProductList();
    },
    async loadProductList() {
      if (this.loadingStatus === 'loading' || this.loadingStatus === 'noMore') {
        return;
      }
      this.loadingStatus = 'loading';
      try {
        const res = await getGoodsListByCategory(this.currentCategoryId, this.queryParams);
        const newProducts = res.rows || [];
        this.productList.push(...newProducts);
        this.checkIfNoMore(newProducts);
      } catch (error) {
        console.error('商品列表加载失败', error);
        this.loadingStatus = 'more';
      }
    },
    loadMoreProducts() {
      if (this.loadingStatus === 'more') {
        this.queryParams.pageNum++;
        this.loadProductList();
      }
    },
    checkIfNoMore(newList) {
      if (newList.length < this.queryParams.pageSize) {
        this.loadingStatus = 'noMore';
      } else {
        this.loadingStatus = 'more';
      }
    },
    // 新增：商品详情跳转
    goToProductDetail(id) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${id}`
      });
    },
    // 新增：加入购物车
    handleAddCart(product) {
      // 判断是否登录
      const userId = this.$store?.state?.user?.id || uni.getStorageSync('userId');
      if (!userId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login' });
        }, 800);
        return;
      }
      addCart({ userId, productId: product.id, quantity: 1, checked: 1 }).then(res => {
        if (res.code === 200) {
          uni.showToast({ title: '加入购物车', icon: 'success' });
        } else {
          uni.showToast({ title: res.msg || '加入失败', icon: 'none' });
        }
      }).catch(() => {
        uni.showToast({ title: '加入失败', icon: 'none' });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.category-page { 
  background: #fff; 
  min-height: 100vh; 
  position: relative; 
  /* 确保页面可以正常滚动 */
  overflow-y: auto;
  /* 设置页面容器为flex布局 */
  display: flex;
  flex-direction: column;
}
.search-bar { padding: 20rpx 20rpx 0 20rpx; background: #fff; }
.level1-scroll {
  display: flex; white-space: nowrap; padding: 10rpx 0; background: #fff; border-bottom: 1rpx solid #eee;
  .level1-item {
    display: inline-block; text-align: center; margin: 0 20rpx;
    .level1-img { width: 80rpx; height: 80rpx; border-radius: 50%; background: #f2f2f2; }
    .level1-name { display: block; font-size: 24rpx; margin-top: 8rpx; }
    &.active { border: 2rpx solid #ff4d4f; border-radius: 50%; }
  }
}
/* 悬浮全部分类按钮样式（纯文字） */
.float-all-btn {
  position: absolute;
  top: 120rpx;
  right: 30rpx;
  z-index: 20;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 110rpx;
  height: 60rpx;
  background: linear-gradient(90deg, #ffb3b3 0%, #ff4d4f 100%);
  border-radius: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(255,77,79,0.15);
  padding: 0 32rpx;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
  border: 1rpx solid #ff4d4f;
  .float-all-text {
    font-size: 26rpx;
    color: #fff;
    font-weight: bold;
    letter-spacing: 2rpx;
  }
  &:active {
    background: linear-gradient(90deg, #ff4d4f 0%, #ffb3b3 100%);
    box-shadow: 0 2rpx 8rpx rgba(255,77,79,0.10);
  }
}
.all-category-modal {
  position: fixed; left: 0; top: 0; width: 100vw; height: 100vh; z-index: 999;
  background: rgba(0,0,0,0.3);
  display: flex; flex-direction: column; align-items: center; justify-content: flex-start;
  .all-category-content {
    width: 100vw; background: #fff; border-radius: 0 0 30rpx 30rpx; padding-bottom: 30rpx;
    .all-title { font-size: 32rpx; font-weight: bold; padding: 30rpx 0 10rpx 30rpx; }
    .all-category-list {
      display: flex; flex-wrap: wrap; justify-content: flex-start; padding: 0 20rpx;
      .all-category-item {
        width: 20%; margin-bottom: 30rpx; display: flex; flex-direction: column; align-items: center;
        .all-category-img { width: 90rpx; height: 90rpx; border-radius: 50%; }
        .all-category-name { font-size: 24rpx; margin-top: 8rpx; }
        &.active { color: #ff4d4f; font-weight: bold; }
      }
    }
    .all-close-btn {
      text-align: center; color: #ff4d4f; font-size: 28rpx; margin-top: 10rpx;
    }
  }
}
.main-content { 
  display: flex; 
  flex: 1;
  /* 确保主内容区域可以正常显示 */
  min-height: 0;
}
.level2-scroll {
  width: 160rpx; 
  background: #f7f7f7; 
  /* 调整高度，避免被底部导航栏遮挡 */
  height: calc(100vh - 200rpx - 120rpx); /* 减去顶部区域和底部导航栏高度 */
  .level2-item { 
    padding: 30rpx 0; 
    text-align: center; 
    font-size: 26rpx; 
    color: #555;
    &.active { 
      color: #ff4d4f; 
      font-weight: bold; 
      background: #fff; 
    }
  }
}
.product-area { 
  flex: 1; 
  padding: 20rpx; 
  /* 确保商品区域可以正常滚动 */
  overflow-y: auto;
}
.filter-tabs { display: flex; justify-content: flex-start; margin-bottom: 20rpx;
  text { padding: 10rpx 30rpx; border-radius: 20rpx; font-size: 28rpx; color: #666; margin-right: 20rpx; }
  .active { background: #ffeded; color: #ff4d4f; }
}
.product-item { display: flex; margin-bottom: 20rpx; padding-bottom: 20rpx; border-bottom: 1rpx solid #f2f2f2;
  .product-image { width: 180rpx; height: 180rpx; border-radius: 8rpx; flex-shrink: 0; margin-right: 20rpx; background: #f2f2f2; }
  .product-info { flex: 1; display: flex; flex-direction: column; justify-content: space-between; min-width: 0;
    .product-name { font-size: 28rpx; color: #333; font-weight: bold; }
    .product-desc { font-size: 24rpx; color: #999; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .price-line { display: flex; justify-content: space-between; align-items: center;
      .product-price { font-size: 32rpx; color: #e54d42; font-weight: bold; }
    }
  }
}
.product-sales {
  color: #999;
  font-size: 24rpx;
  margin-left: 16rpx;
}
</style>